package com.hxzy.controller.admin;

import com.hxzy.common.consts.RedisConst;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.vo.R;
import com.hxzy.dto.AdminLoginDTO;
import com.hxzy.service.SysUserService;
import com.hxzy.service.impl.TokenService;
import com.hxzy.vo.AdminLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

@Api(tags = "后台用户/商家登录API")
@RestController
@RequestMapping(value = "/api")
public class AdminLoginController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private TokenService tokenService;

    @ApiOperation(value = "登录")
    @PostMapping(value = "/login")
    public R login(@RequestBody @Valid AdminLoginDTO adminLoginDTO){
        //验证验证码是否过期
        String redisKey= RedisConst.getRedisKey(RedisConst.CAPTCHA_KEY,adminLoginDTO.getUuid());
        //查询键是不是存在
        Object redisValue=this.redisTemplate.opsForValue().get(redisKey);

        if(redisValue==null){
            return R.build(AckCode.SMS_CODE_OVERTIME);
        }
        //再判断值是否相等
        if(!redisValue.toString().equalsIgnoreCase(adminLoginDTO.getCode())){
            return R.build(AckCode.SMS_CODE_WRONG);
        }
        //验证码验证成功，删除验证码
        this.redisTemplate.delete(redisKey);

        //用户登录
        AdminLoginVO adminLoginVO = this.sysUserService.login(adminLoginDTO);

        //换令牌
        String jwtToken = this.tokenService.createJwtToken(adminLoginVO);

        //之前这个用户让它失效
        Object hashRedisValue = this.redisTemplate.opsForHash().get(RedisConst.ADMIN_LOGIN_ALL, adminLoginVO.getSysUserShopVO().getUserId()+"");
        //该账户有登录过
        if(hashRedisValue!=null){
           String uuidValue=hashRedisValue.toString();
           String stringRedisKey=RedisConst.getRedisKey(RedisConst.ADMIN_LOGIN_KEY,uuidValue);
           //删除之前的登录uuid
           this.redisTemplate.delete(stringRedisKey);
        }
        //写入本次的登录uuid
        this.redisTemplate.opsForHash().put(RedisConst.ADMIN_LOGIN_ALL, adminLoginVO.getSysUserShopVO().getUserId()+"", adminLoginVO.getUuid());

        return R.okHasData(jwtToken);
    }

}
